{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-form-selected dl{z-index: 1000;}
	.multiple-uploading{display: flex;flex-wrap: wrap;}
	.multiple-uploading .multiple-item{position: relative;display: flex;justify-content: center;align-items: center;flex-direction: column;margin-bottom: 10px;padding: 10px;width: 100px;height: 100px;border: 1px dashed #ddd;text-align: center;box-sizing: border-box;line-height: 1;color: #5a5a5a;}
	.multiple-uploading .multiple-item p{line-height: 20px;}
	.multiple-uploading .multiple-item span{display: none;position: absolute;top: -10px;right: -7px;width: 20px;height: 20px;border: 1px solid #999;color: #999;background-color: #fff;border-radius: 50%;line-height: 1;font-size: 18px;cursor: pointer;}
	.multiple-uploading .multiple-item:hover .icon{display: block;}
	.multiple-uploading .multiple-item ~ .multiple-item{margin-left: 10px;}
	#multiple_uploading{cursor: pointer;}
	.multiple-item img{max-width: 100%;max-height: 100%;}
	.shopping-lightspot{width: 290px;}
	.shopping-lightspot .add-lightspot{cursor: pointer;}
	.shopping-lightspot .add-lightspot, .shopping-lightspot .lightspot-item{padding: 15px;border: 1px dashed #e5e5e5;line-height: 1;}
	.shopping-lightspot .lightspot-item{position: relative;display: flex;align-items: center;margin-bottom: 10px;white-space: nowrap;}
	.shopping-lightspot .lightspot-item span{position: absolute;top: -10px;right: -9px;display: none;text-align: center;width: 20px;height: 20px;border: 1px solid #999;border-radius: 50%;font-size: 18px;color: #999;background: #fff;}
	.shopping-lightspot .lightspot-item:hover span{display: block;cursor: pointer;}
	.shopping-lightspot .lightspot-item input{margin-left: 5px;}
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
	<div class="layui-colla-item">
		<h2 class="layui-colla-title">操作提示</h2>
		<ul class="layui-colla-content layui-show">
			<li>管理员可以在此页添加店铺笔记</li>
		</ul>
	</div>
</div>

<div class="layui-form ns-form">

	<div class="layui-form-item">
		<label class="layui-form-label img-upload-lable ns-short-label"><span class="required">*</span>笔记标题：</label>
		<div class="layui-input-inline">
			<input type="text" name="note_title" lay-verify="required" maxlength="40" autocomplete="off" placeholder="笔记标题最多40个字" class="layui-input ns-len-long">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label img-upload-lable ns-short-label">摘要：</label>
		<div class="layui-input-inline">
			<textarea name="note_abstract" class="layui-textarea ns-len-long"></textarea>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>封面：</label>
		<div class="layui-input-inline">
			<input type="radio" name="cover_type" value="0" title="单图" lay-filter="cover_type" checked>
			<input type="radio" name="cover_type" value="1" title="多图" lay-filter="cover_type">
		</div>
	</div>

	<!-- 图片上传 -->
	<div class="layui-form-item">
		<label class="layui-form-label img-upload-lable"></label>
		<div class="layui-input-block img-upload">
			<div class="upload-img-block square simple-uploading">
				<div class="upload-img-box" id="img">
					<div class="ns-upload-default">
						<img src="SHOP_IMG/upload_img.png" />
						<p>点击上传</p>
					</div>
				</div>
			</div>

			<div class="multiple-uploading layui-hide">
				<div class="multiple-item" id="multiple_uploading">
					<img src="SHOP_IMG/upload_img.png" />
					<p>点击上传</p>
				</div>
			</div>
		</div>
		<div class="ns-word-aux">推荐使用 750x420 像素的图片 最多上传1张</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>笔记分组：</label>
		<div class="layui-input-inline">
			<select name="group_id" lay-verify="required">
				<option value="">请选择</option>
				{foreach $group_list as $v}
				<option value="{$v['group_id']}">{$v['group_name']}</option>
				{/foreach}
			</select>
		</div>
	</div>

	<div class="layui-form-item goods_list">
		<label class="layui-form-label"><span class="required">*</span>选择商品：</label>
		<div class="layui-input-block">

			<table id="selected_goods_list"></table>
			<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>正文：</label>
		<div class="layui-input-inline">
			<script id="editor" type="text/plain" class="ns-special-length" style="height:500px;"></script>
            <input type="hidden" name="note_content" id="note_content" />
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">发布时间：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_show_release_time" value="1" title="显示" checked>
			<input type="radio" name="is_show_release_time" value="0" title="不显示">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">阅读次数：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_show_read_num" value="1" title="显示" checked>
			<input type="radio" name="is_show_read_num" value="0" title="不显示">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">点赞次数：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_show_dianzan_num" value="1" title="显示" checked>
			<input type="radio" name="is_show_dianzan_num" value="0" title="不显示">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">虚拟阅读数：</label>
		<div class="layui-input-inline">
			<input type="number" min="0" name="initial_read_num"  class="layui-input">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">虚拟点赞数：</label>
		<div class="layui-input-inline">
			<input type="number" min="0" name="initial_dianzan_num"  class="layui-input">
		</div>
	</div>

	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">立即发布</button>
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="saveDrafts">保存至草稿箱</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>

	<input type="hidden" name="goods_ids" value="" />
	<input type="hidden" name="note_type" value="{$note_type}" />
</div>

<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="ns-table-btn">
		<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
	</div>
</script>

{/block}
{block name="script"}

<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>

    //实例化富文本
    var ue = UE.getEditor('editor');
    if($("#note_content").val()){
        ue.ready(function() {
            ue.setContent($("#note_content").val());
        });
    }

    var form,upload,repeat_flag,
		IMAGE_MAX = 9, //最多可以上传多少张图片
		imageCollection = [], //图片集合
		selectedGoodsId = [],
		goods_id = [],
		goods_list =[];

    layui.use(['form', 'upload'], function() {
		form = layui.form;
		upload = layui.upload;
		repeat_flag = false;

		form.render();

		/**
		 * 图片切换
		 */
		form.on('radio(cover_type)', function(data){
			//0单图  1多图
			if (data.value == 0){

				if(imageCollection.length) {
					imageCollection.splice(1, imageCollection.length);
					var val = '<img src="' + ns.img(imageCollection[0]) + '" alt="">';
					$("#img").html(val);
				}


				$(".simple-uploading").removeClass("layui-hide");
				$(".multiple-uploading").addClass("layui-hide");

				$(".simple-uploading").parents(".layui-form-item").find('.ns-word-aux').text('推荐使用 750x420 像素的图片 最多上传1张');

			} else{
				if(imageCollection.length) {
					var html = '';
					html += `<div class="multiple-item" id="multiple_uploading">`;
					html += `<img src="SHOP_IMG/upload_img.png" />`;
					html += `<p>点击上传</p>`;
					html += `</div>`;

					for (var i = 0; i < imageCollection.length; i++) {
						html += `<div class="multiple-item">`;
						html += `<img src="${ns.img(imageCollection[i])}" alt="">`;
						html += `<span class="icon">x</span>`;
						html += `</div>`;
					}


					$(".multiple-uploading").html(html);
				}

				$(".simple-uploading").addClass("layui-hide");
				$(".multiple-uploading").removeClass("layui-hide");

				$(".simple-uploading").parents(".layui-form-item").find('.ns-word-aux').text('推荐使用 350x350 像素的图片，最多上传9张');
			}
		});

		// 单图片上传
		var uploadInst = upload.render({
			elem: '#img',
			url: ns.url("shop/upload/image"),
			done: function(res) {
				if (res.code >= 0) {
					$("#cover_img_one").val(res.data.pic_path);
					$("#img").html("<img src=" + ns.img(res.data.pic_path) + " >");

					imageCollection = [];
					imageCollection.push(res.data.pic_path)
				}
				return layer.msg(res.message);
			}
		});

		//多图上传
		$("body").on("click","#multiple_uploading", function () {
			var html = '';
			openAlbum(function (data) {
				for (var i = 0; i < data.length; i++) {
					if (imageCollection.length < IMAGE_MAX){
						imageCollection.push(data[i].pic_path);

						html += `<div class="multiple-item">`;
							html += `<img src="${ns.img(data[i].pic_path)}" alt="">`;
							html += `<span class="icon">x</span>`;
						html += `</div>`;
					}
				}
				if (imageCollection.length >= IMAGE_MAX)
					$("#multiple_uploading").addClass("layui-hide");

				$(".multiple-uploading").append(html);

			}, IMAGE_MAX);
		});

		$("body").on('click', '.multiple-item .icon', function () {
			var index = $(this).parent().index() - 1;
			imageCollection.splice(index,1);
			$(this).parent().remove();

			if (imageCollection.length < IMAGE_MAX)
				$("#multiple_uploading").removeClass("layui-hide");
		});



        /**
         * 表单提交(立即发布)
         */
        form.on('submit(save)', function(data){
            field = data.field;
            field.status = 1;
            formSubmit(field)
        });


        /**
         * 表单提交(草稿箱)
         */
        form.on('submit(saveDrafts)', function(data){
            field = data.field;
            field.status = 0;

            formSubmit(field)
        });
    });

    /**
     *  提交
     */
    function formSubmit(data)
    {
		if (selectedGoodsId.length == 0) {
			layer.msg('请选择参与活动的商品！', {icon: 5, anim: 6});
			return;
		}

		data.cover_img = imageCollection.join();

		var goodsHighlights = [];
		$(".lightspot-item").each(function (index,item) {
			goodsHighlights.push($(item).find('input').val());
		});
		data.goods_highlights = goodsHighlights.toString();

		if (!ue.getContentTxt()){
			layer.msg("笔记内容不能为空");
			return false;
		}
		data.note_content = ue.getContentTxt();


		if(repeat_flag) return;
		repeat_flag = true;

		$.ajax({
			type: 'POST',
			dataType: 'JSON',
			url: ns.url("notes://shop/notes/add"),
			data: data,
			async: false,
			success: function(res){
				repeat_flag = false;

				if (res.code == 0) {
					layer.confirm('添加成功', {
						title:'操作提示',
						btn: ['返回列表', '继续添加'],
						yes: function(){
							location.href = ns.url("notes://shop/notes/lists");
						},
						btn2: function() {
							location.href = ns.url("notes://shop/notes/add");
						}
					});
				}else{
					layer.msg(res.message);
				}
			}
		})
    }



    // 表格渲染
	renderTable();
    function renderTable(goods_list = []) {
        //展示已知数据
        table = new Table({
            elem: '#selected_goods_list',
            cols: [
                [{
                    field: 'goods_name',
                    title: '商品名称',
                    unresize: 'false',
                    width: '50%'
                }, {
                    field: 'price',
                    title: '商品价格(元)',
                    unresize: 'false',
                    align: 'right',
                    width: '20%',
                    templet: function(data) {
                        return '￥' + data.price;
                    }
                }, {
                    field: 'goods_stock',
                    title: '库存',
                    unresize: 'false',
                    align: 'center',
                    width: '20%'
                }, {
                    title: '操作',
                    toolbar: '#operation',
                    unresize: 'false',
                    width: '10%'
                }],
            ],
            data: goods_list
        });
    }

	/* 添加商品 */
	function addGoods(){
		goodsSelect(function (res) {
			if (!res.length) return false;
			for(var i=0;i<res.length;i++) {
				goods_id.push(res[i].goods_id);
				goods_list.push(res[i]);
			}

			renderTable(goods_list);
			$("input[name='goods_ids']").val(goods_id.toString());
			selectedGoodsId = goods_id;

		},selectedGoodsId, {mode: "spu"});
	}

    // 删除选中商品
    function delGoods(id) {
        var i, j;
        $.each(goods_list, function(index, item) {
            var goods_id = item.goods_id;

            if (id == Number(goods_id)) {
				goods_list.splice(index, 1);
				renderTable(goods_list);
            }
        });


        $.each(selectedGoodsId, function(index, item) {
            if (id == Number(item)) {
				selectedGoodsId.splice(index, 1);
				goods_id = selectedGoodsId;
            }
        });
        $("input[name='goods_ids']").val(goods_id.toString());
    }

    function back() {
        location.href = ns.url("notes://shop/notes/lists");
    }
</script>
{/block}